// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NativeEventEmitter, DeviceEventEmitter, Image, TextInput, NativeModules, Platform, StyleSheet, ScrollView, Text, View, TouchableOpacity, TouchableHighlight, Alert, InteractionManager } from 'react-native';
import * as ActionTypes from '../../constants/constants.js';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { Echarts, echarts } from 'react-native-secharts';
import moment from 'moment';
import { Actions } from 'react-native-router-flux';
import BleManager from 'react-native-ble-manager';

// const BleManagerModule = NativeModules.BleManager;
// const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);

// antd 按需加载
import { Tabs, Toast, Button, ListView, ActivityIndicator, Portal } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { } from './module/module.js'
import { deviceHeartRate, deviceHeartRateDetail, deviceHeartRateList } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, Results } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, ScreenWidth, saveData, removeData, loadData, bodyPlus, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'
class Data extends Component {

  constructor(props) {
    super(props)
    this.state = {
      deviceList: [],
      loading: false,
      bodyData: []
    }

  }


  componentDidMount() {
    const { dispatch, myDevice } = this.props
    // 从缓存取设备信息
    console.log('开始读取')
    loadData('myDevice').then((device) => {
      console.log(device, '本地存储的 device')
      if (device) {
        console.log(device, '本地存储的 device')
        dispatch({
          type: ActionTypes.setMyDevice,
          data: device
        })
      }
    });
    // 搜索的设备列表
    bodyPlus.deviceList((e) => {
      console.log(e)
      this.setState({
        deviceList: JSON.parse(e.eventProperty),
      })
      Portal.remove(this.loading)
    })
    // 重连成功的回调
    bodyPlus.connectDeviceSuccess((e) => {
      Portal.remove(this.loading)
      dispatch({
        type: ActionTypes.setMyDevice,
        data: JSON.parse(e.eventProperty)
      })
      // console.log('连接我的设备成功')
    })
    // 监控电量
    bodyPlus.powerLevel((e) => {
      Portal.remove(this.loading)
      dispatch({
        type: ActionTypes.setPowerLevel,
        data: JSON.parse(e.eventProperty)
      })
    })
    // 信号更改反馈
    bodyPlus.rssi((e) => {
      console.log(e)
      dispatch({
        type: ActionTypes.setRssi,
        data: JSON.parse(e.eventProperty)
      })
    })
    // 离线状态
    bodyPlus.offlineStatus((e) => {
      console.log(e)
      dispatch({
        type: ActionTypes.setOfflineStatus,
        data: JSON.parse(e.eventProperty)
      })
    })
    // 心率的回调
    bodyPlus.dataCallBack((e) => {
      // console.log(e)
      let bodyData = [...this.state.bodyData]
      let bodyDataItem = JSON.parse(e.eventProperty)
      bodyDataItem.date = new Date()
      bodyData.push(bodyDataItem)
      this.setState({
        bodyData
      })
      // dispatch({
      //   type: ActionTypes.setOfflineStatus,
      //   data: JSON.parse(e.eventProperty)
      // })
    })
    console.log(BleManager)
    BleManager.start({ showAlert: false })
      .then(() => {
        // Success code
        console.log('Module initialized');
      });
  }

  checkState() {
    // return new Promise((resolve, reject) => {
    //   bleManagerEmitter.addListener(
    //     'BleManagerDidUpdateState',
    //     (args) => {
    //       if (args.state == 'off') {
    //         Toast.info('请打开蓝牙', 1)
    //         reject()
    //         return
    //       }
    //       resolve(args)
    //       console.log(args)
    //       // The new state: args.state
    //     }
    //   );
    //   BleManager.checkState();
    // })
  }




  connectDeviceBySn() {
    const { myDevice, connectStatus } = this.props
    if (myDevice && myDevice.sn) {
      // this.checkState().then(res => {
      this.loading = Toast.loading('连接中', 0)
      console.log(myDevice.sn, '通过 sn 连接中')
      if (connectStatus) {
        bodyPlus.disConnect(() => {
          bodyPlus.connectDeviceBySn(myDevice.sn)
        })
      } else {
        bodyPlus.connectDeviceBySn(myDevice.sn)
      }
      // })
    }
  }

  search() {
    // this.checkState().then(res => {
    this.loading = Toast.loading('查找中')
    bodyPlus.search()
    // })
  }

  connectDevice(device) {
    console.log(device, '连接的设备')
    bodyPlus.connectDevice(device.macAddress, device.deviceSn, device.rssi, device.deviceName, device.isDfuStatus)
  }

  startOffline() {
    bodyPlus.startOffline()
  }

  finishOffline() {

    bodyPlus.finishOffline()
  }

  startEcg() {
    const { dispatch } = this.props
    dispatch({
      type: ActionTypes.setEcgStatus,
      data: true
    })
    this.time = 60
    this.startEcgTime = setInterval(() => {
      console.log(this.time)
      if (this.time <= 0) {
        clearInterval(this.startEcgTime)
        this.closedEcg()
      }
      this.time--
    }, 1000)
    bodyPlus.startEcg()
  }

  closedEcg() {
    const { dispatch } = this.props
    const { bodyData } = this.state
    dispatch({
      type: ActionTypes.clearEcgStatus,
    })
    bodyPlus.closedEcg()
    deviceHeartRate({
      data: bodyData,
      dmData: bodyData[bodyData.length - 1]
    }).then(res => {
      Toast.success('保存成功')
      console.log(res)
    }).finally(() => {
      this.setState({
        bodyData: []
      })
    })
  }

  reName() {
    bodyPlus.reName('xyy')
  }

  disConnect() {
    const { dispatch } = this.props
    bodyPlus.disConnect()
  }
  deleteMyDevice() {
    const { dispatch } = this.props
    dispatch({
      type: ActionTypes.clearMyDevice
    })
    bodyPlus.disConnect()
  }


  componentWillUnmount() {
    this.disConnect()
  }


  render() {
    const { myDevice, offlineStatus, connectStatus, ecgStatus } = this.props
    const { deviceList, loading, bodyData } = this.state
    console.log(bodyData, 522525252)
    let newBodyData = bodyData.filter(item => item.code == 3).map((item, index) => {
      return {
        x: moment(item.date).format('HH:mm:ss'),
        y: item.dm,
      }
    })
    console.log(newBodyData)
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="健康数据"
          extra="心率记录"
          extraOnPress={() => Actions.rateList({ id: null })}
        />
        <ScrollView style={Style.content}>
          <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 20 }}>
            <Button onPress={() => this.search()}>查找设备</Button>
          </View>
          {myDevice && (
            <View style={{}}>
              <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 20 }}>
                <Button onPress={() => this.deleteMyDevice()}>删除设备</Button>
              </View>
            </View>
          )}


          {/* <Button onPress={() => this.search()}>断开</Button> */}
          {/* <TextInput placeholder='修改名称'
            onChange={(e) => {
              console.log(e)
              this.name
            }}></TextInput>
          <TouchableHighlight
            onPress={() => this.reName()}
            style={{
              padding: 20
            }}
          >
            <Text>修改名称</Text>
          </TouchableHighlight> */}
          {/* <TouchableHighlight
          onPress={() => this.showDeviceLists()}
        >
          <Text>显示设备列表</Text>
        </TouchableHighlight> */}
          {myDevice ? (
            <View style={{ marginTop: 20 }}>
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                padding: 15,
                backgroundColor: '#fff'
              }}>
                <View style={{}}>
                  <Image resizeMode='cover' style={{ width: 60, height: 60 }} source={require('../../static/images/bodyplus.png')} />
                </View>
                <View style={{
                  flex: 1,
                  height: 60,
                  marginLeft: 15
                }}>
                  <View style={{}}>
                    <Text style={{ fontSize: 20, color: '#61676F', lineHeight: 22, marginBottom: 10 }}>{myDevice.bleName}</Text>
                  </View>
                  <View style={{}}>
                    <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{myDevice.sn}</Text>
                  </View>
                </View>
                <View style={{
                }}>
                  {!connectStatus ? <Button onPress={() => this.connectDeviceBySn()}>连接</Button> : <Button onPress={() => this.disConnect()}>断开连接</Button>}
                </View>
              </View>
              <View style={{}}>
                {ecgStatus && connectStatus && <Button onPress={() => this.closedEcg()}>关闭采集</Button>}
                {!ecgStatus && connectStatus && <Button onPress={() => this.startEcg()}>采集心率</Button>}
              </View>
              <View style={{}}>
                {offlineStatus && connectStatus && <Button onPress={() => this.finishOffline()}>关闭离线</Button>}
                {!offlineStatus && connectStatus && <Button onPress={() => this.startOffline()}>开启离线</Button>}
              </View>
            </View>
          ) : null}
          {bodyData && bodyData.length > 0 && (
            <View style={{}}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{bodyData[bodyData.length - 1].status}</Text>
              {newBodyData.length > 1 && (
                <Echarts option={{
                  xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: newBodyData.map((item) => item.x)
                  },
                  yAxis: {
                    type: 'value'
                  },
                  series: [{
                    data: newBodyData.map((item) => item.y),
                    type: 'line',
                  }]
                }} height={400} />
              )}

            </View>
          )}
          {!deviceList || deviceList.length <= 0 && <Results type='data' width={size(500)} height={size(200)} />}
          {deviceList.map((item, index) => {
            return (
              <TouchableOpacity onPress={() => {
                this.loading = Toast.loading('连接中', 0)
                this.connectDevice(item)
              }} style={{}} key={index}>
                <View style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  padding: 15,
                  marginTop: 15,
                  backgroundColor: '#fff'
                }}>
                  <View style={{}}>
                    <Image resizeMode='cover' style={{ width: 60, height: 60 }} source={require('../../static/images/bodyplus.png')} />
                  </View>
                  <View style={{
                    flex: 1,
                    height: 60,
                    marginLeft: 15
                  }}>
                    <View style={{}}>
                      <Text style={{ fontSize: 20, color: '#61676F', lineHeight: 22, marginBottom: 10 }}>{item.deviceName}</Text>
                    </View>
                    <View style={{}}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.deviceSn}</Text>
                    </View>

                    {/* <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.macAddress}</Text> */}
                    {/* <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.deviceSn}</Text> */}
                    {/* <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.deviceName}</Text> */}
                  </View>
                  <View style={{
                  }}>
                    {item.rssi == 0 ? <MaterialCommunityIcons name="signal-cellular-outline" /> : null}
                    {item.rssi < 0 && item.rssi >= -30 ? <MaterialCommunityIcons name="signal-cellular-1" size={30} /> : null}
                    {item.rssi < -30 && item.rssi >= -70 ? <MaterialCommunityIcons name="signal-cellular-2" size={30} /> : null}
                    {item.rssi < -70 && item.rssi > -100 ? <MaterialCommunityIcons name="signal-cellular-3" size={30} /> : null}
                  </View>
                </View>
              </TouchableOpacity>
            )
          })}
        </ScrollView>
      </View >
    );
  }
}


export default connect(({ user, myDevice, offlineStatus, connectStatus, ecgStatus }) => ({
  user, myDevice, offlineStatus, connectStatus, ecgStatus
}))(pureRender(Data))
